package com.example.quartz.controller;

import lombok.extern.slf4j.Slf4j;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author: dangwen
 * @createDate: 2022/4/4
 */
@RestController
@Slf4j
public class QuartzController {

    @Autowired
    @Qualifier("schedulerFactoryBean")
    private Scheduler scheduler;

    @GetMapping("/pause")
    public String pause() throws SchedulerException {
        // 指定暂停的任务
        JobKey jobKey = new JobKey("jobDetailFirst");
        scheduler.pauseJob(jobKey);
        log.info("关闭任务成功");
        return "pause";
    }

    @GetMapping("/start")
    public String start() throws SchedulerException {
        // 指定暂停的任务
        JobKey jobKey = new JobKey("jobDetailFirst");
        scheduler.resumeJob(jobKey);
        log.info("关闭任务成功");
        return "start";
    }

    public String trigger() throws SchedulerException {
        // 获取任务
        JobKey jobKey = new JobKey("jobDetailFirst");
        // 获取 jobDetail
        JobDetail jobDetail = scheduler.getJobDetail(jobKey);
        // 生成 trigger
        Trigger trigger = TriggerBuilder.newTrigger().withSchedule(SimpleScheduleBuilder.repeatSecondlyForever(1)).build();
        // 删除原有任务，因为后续会以此任务名称进行重建任务
        scheduler.deleteJob(jobKey);
        // 启动任务
        scheduler.scheduleJob(jobDetail, trigger);
        log.info("任务修改成功，当前任务执行时间为{1}秒");
        return "trigger";
    }
}
